package cn.cp.baseframe.controller;

import cn.cp.baseframe.model.dto.UserDTO;
import cn.cp.baseframe.model.req.UserQueryReq;
import cn.cp.baseframe.model.req.UserReq;
import cn.cp.baseframe.model.vo.UserVO;
import cn.cp.baseframe.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author chenchaoqi
 * @since 2022-03-13
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService iUserService;

    @GetMapping("/query")
    public List<UserVO> query(UserReq userReq) {
        List<UserVO> result = new ArrayList<>();
        List<UserDTO> userList = iUserService.query();
        if (userList != null && userList.size() > 0) {
            for (UserDTO u : userList) {
                UserVO userVO = new UserVO();
                userVO.setId(u.getId());
                userVO.setName(u.getName());
                userVO.setAge(u.getAge());
                result.add(userVO);
            }
        }
        return result;
    }

    @GetMapping("/page")
    public List<UserVO> page(UserQueryReq req) {
        if(req.getPageIndex() <= 0 || req.getPageSize() <= 0){
            return null;
        }

        List<UserVO> result = new ArrayList<>();
        List<UserDTO> userList = iUserService.page(req.getPageIndex(),req.getPageSize());
        if (userList != null && userList.size() > 0) {
            for (UserDTO u : userList) {
                UserVO userVO = new UserVO();
                userVO.setId(u.getId());
                userVO.setName(u.getName());
                userVO.setAge(u.getAge());
                result.add(userVO);
            }
        }
        return result;
    }


    @PostMapping
    public Integer insert(Integer id, String name, Integer age, UserReq userReq) {
        UserReq req = new UserReq();
        req.setId(id);
        req.setAge(age);
        req.setName(name);
        return iUserService.insert(req);
    }

    @PutMapping
    public Integer update(Integer id, String name, Integer age, UserReq userReq) {
        UserReq req = new UserReq();
        req.setId(id);
        req.setAge(age);
        req.setName(name);
        return iUserService.update(req);
    }

    @DeleteMapping
    public Integer delete(Integer id) {
        return iUserService.delete(id);
    }
}
